package com.cow.net.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

/**
 * @author 作者 YYD
 * @version 创建时间：2016年11月18日 下午9:00:11
 * @function 未添加
 */
public class UdpProverbClient {

	EventLoopGroup group ;
	  Bootstrap b;
	  String context;

	public UdpProverbClient(EventLoopGroup group, Bootstrap b) {
		this.group = group;
		this.b = b;
	}

	public void run(int port) throws Exception{

		try {

			b.group(group).channel(NioDatagramChannel.class)
					.option(ChannelOption.SO_BROADCAST,false)//允许广播
					.handler(new UdpProverClientHandler());//设置消息处理器
			Channel ch = b.bind(0).sync().channel();
			//向网段内的所有机器广播UDP消息。

				ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(context, CharsetUtil.UTF_8), new InetSocketAddress("127.0.0.1", port))).sync();

			  if (!ch.closeFuture().await(15000)) {
				 System.out.println("查询超时！");


			}

			//wait(15000);
		} catch (Exception e) {
			group.shutdownGracefully();
		}

	}
	public static void main(String [] args) throws Exception{
		int port = 9999;
		EventLoopGroup group  = new NioEventLoopGroup();
		/*while (true) {*/
		Bootstrap b = new Bootstrap();

			new UdpProverbClient(group ,b).run(port);
		/*}*/

	}
}
